import { TableColumnType } from "../../interface";
import { useEffect, useState } from "react";
import { codeErrorAPI } from "../../apis/error";
import { Button, Form, Input, Tabs, Space, DatePicker, Table } from "antd";
import { Link, useRouteMatch, useLocation, useHistory } from 'react-router-dom';
import ErrorMetrics from "./common/error-metrics";
import moment, { Moment } from 'moment';
import qs from 'qs';
import { ReloadOutlined } from "@ant-design/icons";
import TableResizeBtn from "../../component/table-resize-btn";
import { SizeType } from "antd/es/config-provider/SizeContext";
import { fmtTimeStamp } from "../../utils";
import CodeErrorBarChart from "./common/code-error-bar-chart";

const {RangePicker} = DatePicker;
const {TabPane} = Tabs;

const CodeErrorView = () => {
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState([]);
  const [metrics, setMetrics] = useState([]);
  const [pager, setPager] = useState({
    pageIndex: 1,
    pageSize: 10,
    total: 0
  });
  const [tableSize, setTableSize] = useState<SizeType>("middle");
  const [searchData, setSearchData] = useState({
    searchKey: '',
    dateTime: [
      moment().subtract(1, 'd'),
      moment()
    ]
  });

  const h = useLocation();
  const match = useRouteMatch();
  const history = useHistory();
  const query = qs.parse(h.search.substr(1));

  useEffect(() => {
    getTableData();
    codeErrorAPI.getMetrics({}).then((res: any) => {
      if (res && res.success) {
        const list = res.data.map((it: any) => {
          return {
            time: moment(new Date(+it.time)).format("YYYY-MM-DD hh:mm:ss"),
            value: 1
          }
        })
        setMetrics(list);
      }
    })
  }, [pager.pageIndex, searchData]);

  function getTableData() {
    setLoading(true);
    const params = {
      ...pager,
      searchKey: searchData.searchKey,
      sortDirection: "DESC",
      sort: "time",
    }
    if (searchData.dateTime && searchData.dateTime.length) {
      // const fmt = "YYYY-MM-DD";
      // const time = " 00:00:00";
      const setTime = (m: Moment) => {
        m.hour(0).minute(0).second(0);
        return m;
      }
      Object.assign(params, {
        end_time: setTime(searchData.dateTime[1]).unix() * 1000,
        start_time: setTime(searchData.dateTime[0]).unix() * 1000,
      })
    }
    codeErrorAPI.errorGroupList(params).then((res: any) => {
      if (res && res.success) {
        setTableData(res.data.list);
        setPager({
          ...pager,
          total: res.data.total
        })
      }
    }).finally(() => {
      setLoading(false);
    })
  }


  const columns: TableColumnType[] = [
    {
      title: '错误信息',
      dataIndex: 'message',
      key: 'message',
      render: (t: string, record: any) => {
        return (
          <Link to={ match.path + "/" + encodeURIComponent(record.message) }>
            { record.message }
          </Link>
        )
      },
      width: "40%",
      ellipsis: true
    },
    {
      title: '错误类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '最近发生时间',
      dataIndex: 'time',
      key: 'time',
      render: (t: number) => {
        return fmtTimeStamp(+t)
      }
    },
    {
      title: '事件总数',
      dataIndex: 'count',
      key: 'count',
    },
    {
      title: '影响用户',
      dataIndex: 'user_count',
      key: 'user_count',
    },
  ]

  function onFinish(values: any) {
    setSearchData({
      dateTime: values.dateTime || [],
      searchKey: values.searchKey || '',
    })
  }

  function onTabChange(value: string) {
    history.replace(match.url + "?tab=" + value)
  }

  const V1 = (
    <>
      <ErrorMetrics metrics={ metrics }/>
      <CodeErrorBarChart metrics={ metrics }/>
    </>
  );

  const V2 = (
    <>
      <div className={ "ui-t-r" } style={ {
        display: 'flex',
        paddingTop: 10,
        justifyContent: 'space-between',
      } }>
        <Form
          name="basic"
          layout={ "inline" }
          labelCol={ {span: 0} }
          wrapperCol={ {span: 24} }
          initialValues={ searchData }
          onFinish={ onFinish }
        >
          <Form.Item name="searchKey">
            <Input placeholder={ "错误信息" } allowClear={ true } width={ 300 }/>
          </Form.Item>
          <Form.Item name={ "dateTime" }>
            <RangePicker
              allowClear={ false }
              defaultValue={ (searchData as any).dateTime }
              style={ {marginBottom: 16} }
            />
          </Form.Item>
          <Form.Item>
            <Button htmlType={ "submit" } type={ "primary" }>查询</Button>
          </Form.Item>
        </Form>
        <Space size={ "middle" }>
          <a className="ui-hover-text" onClick={ e => e.preventDefault() }>
            <ReloadOutlined onClick={ getTableData }/>
          </a>
          <TableResizeBtn onChange={ setTableSize } defaultKey={ tableSize }/>
        </Space>
      </div>
      <Table
        rowKey={ "id" }
        bordered
        columns={ columns }
        loading={ loading }
        size={ tableSize }
        dataSource={ tableData }
        pagination={ {
          showQuickJumper: false,
          showTotal: () => `共 ${ pager.total } 条`,
          pageSize: pager.pageSize,
          total: pager.total,
          current: pager.pageIndex,
          onChange: (v) => setPager({
            ...pager,
            pageIndex: v,
          })
        } }
      />
    </>
  )

  return (
    <Tabs style={ {marginTop: -16} } onChange={ onTabChange } defaultActiveKey={ query.tab as string || "metrics" }>
      <TabPane tab="异常走势" key="metrics">{ V1 }</TabPane>
      <TabPane tab="异常数据" key="list">{ V2 }</TabPane>
    </Tabs>
  )
}

export default CodeErrorView;